package jvm.FourCharacteristic;

import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.util.LinkedList;
import java.util.List;

/**
 * 虚引用
 * 当对象被回收会有一个通知 通知放在队列中
 */
public class phantomReference {
    private static final List<Object> LIST = new LinkedList<>();
    private static final ReferenceQueue<publicData> QUEUE = new ReferenceQueue<>();

    public static void main(String[] args) {
        PhantomReference<publicData> p = new PhantomReference<>(new publicData(), QUEUE);

        new Thread(() -> {
            while (true) {
                LIST.add(new byte[1024 * 1024]);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(p.get());
            }
        }).start();

        new Thread(() -> {
            while (true) {
                Reference<? extends publicData> poll = QUEUE.poll();
                if (poll != null) {
                    System.out.println("--- 虚引用对象被JVM回收了 ---" + poll);
                }
            }
        }).start();

        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}